from PySide6.QtCore import QObject, Property, Signal, QPointF
from PySide6.QtGui import QColor

from PySide6.QtQuick import (QQuickItem, QSGFlatColorMaterial,
                             QSGGeometry, QSGGeometryNode, QSGNode)
from PySide6.QtQml import QmlElement

QML_IMPORT_NAME = "BppTableModel"
QML_IMPORT_MAJOR_VERSION = 1
@QmlElement
class BTColList(QObject):
    def __init__(self,parent=None):
        super().__init__(parent)


    def getSortColumns(self):

        iCol=1
        sortColumns=[]
        for curColumn in self.defs:
            sortVal = curColumn.sortFlag;
            if(sortVal == 1):
                sortColumns.append(iCol);
            if(sortVal == 2):
                sortColumns.append(-iCol);
            iCol+=1
        

        return sortColumns

    def clear(self):
    #     for(auto col: def){
    #         delete col;
    #     }
        self.defs=[]#.clear();

    def add(self):
        newCol=len(self.defs)
        self.defs.append(TableColumn() )
        return newCol;

    def modifyColumn(self, columnId,  withDefaults, colDef):
        self.defs[columnId].modify(colDef, withDefaults);

    def itemAt(self,columnId):
        return self.defs[columnId];

    def at(self, columnId):
        return self.defs[columnId]

    def getColumnMap(self):

        records=[]

        for col in self.defs:
            records.append({"title": col.title,"dataType": col.type
                ,"sort":col.sortFlag,"action":col.action,"command":col.command
                ,"width":col.width
                ,"minWidth":col.minWidth
                ,"role":col.role})
        return records;

    def resizeColumns(self, theWidth):
        if(len(self.defs) == 0):
            return False;
        if(theWidth <= 0): 
            return False;

        minWidth = 0;
        toResize=[]

        for i in range(self.defs.size()):
            if(self.defs[i].minWidth):
                toResize.append(i);
                minWidth += self.defs[i].minWidth;

        if len(toResize)==0: 
            return False;

        usedWidth = 0;
        for i in range(self.defs.size()):
            if(not i in toResize):
                if(self.defs[i].width):
                    usedWidth += self.defs[i].width;
                else:
                    usedWidth += 100;

        newWidth = theWidth - usedWidth;
        if( newWidth < minWidth ):
            # //mantain min
            for iCol in  toResize:
                self.defs[iCol].width = self.defs[iCol].minWidth 
        else:
            factor = float(newWidth) / float(minWidth);
            for iCol in toResize :
                self.defs[iCol].width = int(floor(float(self.defs[iCol].minWidth) * factor))

        return True

    def size(self):
        return len(self.defs)

    def swapSort(self, columnId):
        sortVal =self.defs[columnId].sortFlag;

        sortVal+=1;
        if(sortVal > 2): 
            sortVal = 0;

        self.defs[columnId].sortFlag = sortVal;
